<?php

declare(strict_types=1);

namespace App\Exception\Handler;

use App\Http\Common\Result;
use App\Http\Common\ResultCode;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Hyperf\RateLimit\Exception\RateLimitException;
use Swow\Psr7\Message\ResponsePlusInterface;
use Throwable;

class RateLimitExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponsePlusInterface $response)
    {
        $this->stopPropagation();
        $res = new Result(
            code: ResultCode::FAIL,
            message: "请求过于频繁",
            data: []
        );
        return $response->withHeader('Content-Type', 'application/json')
            ->withStatus(200)
            ->withBody(new SwooleStream(json_encode($res, JSON_UNESCAPED_UNICODE)));

    }

    public function isValid(\Throwable $throwable): bool
    {
        return $throwable instanceof RateLimitException;
    }
}
